package com.hadoop.mapreduce;

import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
/**
 * 单词统计
 * @date 2015年5月7日 下午5:02:16
 * @author zhouxiao
 */
public class WordCount {
	//map
	public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> {
		private Text word=new Text();
		private IntWritable one=new IntWritable(1);
		
		public void map(Object key, Text value,Context context)throws IOException, InterruptedException {
			System.out.println("key="+key+",value="+value.toString());
			StringTokenizer stringTokenizer=new StringTokenizer(value.toString());
			while (stringTokenizer.hasMoreTokens()) {
				word.set(stringTokenizer.nextToken());
				context.write(word,one);
			}
		}

	}
	//reduce
	public static class IntSumReducer extends Reducer<Text, IntWritable, Text,IntWritable>{
		private IntWritable  result=new IntWritable();
		public void reduce(Text text, Iterable<IntWritable> values,Context context)throws IOException, InterruptedException {
			System.out.println("text="+text+",values="+values.toString());
				int sum=0;
				for (IntWritable intWritable : values) {
					sum+=intWritable.get();
				}
				result.set(sum);
				context.write(text, result);
		}
		
	}
	 public static void main(String[] args) throws Exception {
		    Configuration conf = new Configuration();
		    Job job = new Job(conf, "word count");
		    job.setJarByClass(WordCount.class);
		    job.setMapperClass(TokenizerMapper.class);
		    job.setCombinerClass(IntSumReducer.class);
		    job.setReducerClass(IntSumReducer.class);
		    job.setOutputKeyClass(Text.class);
		    job.setOutputValueClass(IntWritable.class);
		    FileInputFormat.addInputPath(job, new Path("hdfs://master:9000//usr//local//tmp/test//in.txt"));
		    FileOutputFormat.setOutputPath(job, new Path("hdfs://master:9000//usr//local//tmp/test//out"));
		    System.exit(job.waitForCompletion(true) ? 0 : 1);
	}
}
